import 'package:flutter/material.dart';

import 'package:regular_assess/helper/utils/util.dart';

import 'index.dart';

class SearchController extends GetxController
    with GetSingleTickerProviderStateMixin {
  SearchController();

  final state = SearchState();

  void actionSearch() async {
    if (state.inputCtrl.text.isEmpty) {
      return;
    }
    state.historys ??= [];
    if (!state.historys!.contains(state.inputCtrl.text)) {
      state.historys?.insert(0, state.inputCtrl.text);
      SpUtil().setJSON(StorageKeys.search_history, state.historys!);
    }
    requestForSearch(state.inputCtrl.text);
  }

  void actionResultCell(dynamic md) {
    state.historys ??= [];
    if (!state.historys!.contains(md.documentTitle)) {
      state.historys?.insert(0, md.documentTitle ?? '');
      SpUtil().setJSON(StorageKeys.search_history, state.historys!);
    }
    // Get.toNamed(RouterPath.means_detail, arguments: md);
  }

  void getHistory() async {
    List? hs = await SpUtil().getJSON(StorageKeys.search_history);
    if (hs != null) {
      state.historys = hs.cast();
    }
    update();
  }

  void actionDelItem(String s) {
    state.historys?.remove(s);
    SpUtil().setJSON(StorageKeys.search_history, state.historys ?? []);
    update();
  }

  void actionDel() {
    state.historys = null;
    SpUtil().setJSON(StorageKeys.search_history, []);
    update();
  }

  void actionHistoryCell(String s) {
    state.isSearching = true;
    requestForSearch(s);
  }

  void requestForSearch(String s) async {
    // var res = await MeansApi.postDocSearch(
    //   keywords: s,
    //   reportType: state.reportType,
    // );
    // if (res.isSuccess) {
    //   List? records = res.data['records'];
    //   var list = records
    //       ?.map(
    //         (e) => MeansModel.fromJson(e),
    //       )
    //       .toList();
    //   state.results = list;
    //   update();
    // }
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    state.titles = ['政策措施', '招标采购', '审查制度', '违规案例'];
    state.tabCtrl = TPTabBarController(needPage: false)
      ..titles.value = state.titles
      ..index.listen((p0) {
        state.reportType = state.titles[p0];
        actionSearch();
      });

    state.reportType = Get.parameters['reportType'].toString();
    state.inputCtrl = TextEditingController()
      ..addListener(() {
        state.isSearching = state.inputCtrl.text.isNotEmpty;
        update();
      });
    getHistory();

    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
